using System;
using Tools.Common.UnitOfWork.Contracts;
using System.Web;

namespace Web.App.Infrastructure.UnitOfWork.Implementations
{

    public class HttpSessionUoWRepository : IUnitOfWorkRepository
    {
        public IUnitOfWork PickupUnitOfWork(Guid? id)
        {
            IUnitOfWork uow = null;

            if (id != null)
            {
                uow = HttpContext.Current.Session[id.ToString()] as IUnitOfWork;
                if(uow != null)
                    HttpContext.Current.Session.Remove(id.ToString());
            }

            return uow;
        }

        public void SaveUnitOfWork(IUnitOfWork unitOfWork)
        {
            if (unitOfWork == null)
                throw new ArgumentNullException("uow must not be null");

            HttpContext.Current.Session[unitOfWork.ID.ToString()] = unitOfWork;
        }

        public void DisposeUnitOfWork(Guid? id)
        {
            IUnitOfWork uow = null;

            if (id != null)
            {
                uow = HttpContext.Current.Session[id.ToString()] as IUnitOfWork;
                
                if(uow != null)
                    uow.Dispose();
            }

            
        }
    }
}